import {MESSAGE as message} from "./alert.js";

(function () {
    if (!XMLHttpRequest) {
        message.error("你的电脑不支持AJAX请求，无法访问该网站!");
        window.location.go(-1);
    }
    let request = new XMLHttpRequest();
    let defaultOption = {
        url: "", method: "POST", async: false, success: function (data) {

        }, error: function (error) {
            message.error({title: "错误" + request.statusText, btn: ["确定"], content: request.responseText});
        }, data: null, username: null, password: null
    };
    let post = function (options = defaultOption) {
        options.method = "POST";
        other(CheckOptions(defaultOption, options));
    }
    let get = function (options = defaultOption) {
        options.method = "GET";
        other(CheckOptions(defaultOption, options));
    }
    let put = function (options = defaultOption) {
        options.method = "PUT";
        other(CheckOptions(defaultOption, options));
    }
    let del = function (options = defaultOption) {
        options.method = "DELETE";
        other(CheckOptions(defaultOption, options));
    }
    let other = function (options = defaultOption) {
        CheckOptions(defaultOption, options);
        request.onreadystatechange = function () {
            if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
                options.success(request.responseText);
            } else if (request.readyState === XMLHttpRequest.DONE) {
                options.error({code: request.status, errorCode: request.statusText, msg: request.responseText});
            }
        }
        request.open(options.method, options.url, options.async, options.username, options.password);
        request.send(options.data);

    }

    function CheckOptions(baseOption = defaultOption, newOption = defaultOption) {
        if (!newOption) {
            newOption = baseOption;
            return newOption;
        }
        if (newOption instanceof String) {
            baseOption.url = newOption;
            newOption = baseOption;
            return newOption;
        }
        if (!newOption.method) {
            newOption.method = defaultOption.method;
        }
        if (!newOption.url) {
            newOption.url = defaultOption.url;
        }
        if (!newOption.async) {
            newOption.async = defaultOption.async;
        }
        if (!newOption.data) {
            newOption.data = baseOption.data;
        }
        if (!newOption.username) {
            newOption.username = baseOption.username;
        }
        if (!newOption.password) {
            newOption.password = baseOption.password;
        }
        if (!newOption.success) {
            newOption.success = baseOption.success;
        }
        if (!newOption.error) {
            newOption.error = baseOption.error;
        }
        return newOption;
    }

    window.ajax = {post: post, get: get, put: put, del: del, other: other}
})(window)
export let AJAX = ajax;
